Golang : Output or print out JSON stream/encoded data
Problem :
You need to produce JSON stream or JSON encoded data to web browser or client. How to do that?
Solution :
Set the header Content-Type
to application/json
and write the http.ResponseWriter.
For example :
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// NOTE : put jsonStr in a FOR loop to read forever from database and encode the data with
// json.Marshal() function to produce JSON stream
// see https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
// for this example, we will use static JSON string
jsonStr := `[{"Name":"Dennis","Age":16,"Job":"CEO"},
{"Name":"Eva","Age":34,"Job":"CFO"},
{"Name":"Paul","Age":28,"Job":"COO"}]`
// output to web or client
w.Write([]byte(jsonStr))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Employees)
http.ListenAndServe(":8080", mux)
}
Reference :
https://www.socketloop.com/tutorials/golang-unmarshal-json-from-http-response
See also : Golang : Unmarshal JSON from http response
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.1k Unix/Linux/MacOSx : How to remove an environment variable ?
+46.9k Golang : Convert int to byte array([]byte)
+9.7k Golang : Print how to use flag for your application example
+6.4k How to let Facebook Login button redirect to a particular URL ?
+5.3k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+10.5k Golang : How to transmit update file to client by HTTP request example
+7.6k Findstr command the Grep equivalent for Windows
+10.9k Golang : Post data with url.Values{}
+6.9k Linux : How to fix Brother HL-1110 printing blank page problem
+10.1k Android Studio : Checkbox for user to select options example
+5.8k Golang : How to write backslash in string?
+11.9k Golang : Validate email address